const mysql = require("mysql2");
const { promisify } = require('util');
/**
 * 
 * @param inputs.meta  
 * @param inputs.data 参照 测试数据 
 * @param ouputs.meta 
 * @param ouputs.data 参照 结果数据 
 */
function transform (
    inputs = {
        conf: {
            "host": "120.48.125.223",
            "user": "root",
            "password": "jiangshan",
            "port": 53306,
            "database": "pkuquant"
        },
        table: 'demo1',
        data: [],
        exdata: {}
    },
    ouputs = null) {
    // const mysqlPool = mysql.createConnection(inputs.conf);
    var tablename = inputs.table;

    const connection = mysql.createConnection(inputs.conf)
    //连接数据库
    connection.connect((err) => {

        if (err) {
            console.error(`没有连接成功:${err.message}`);
            return;
        }
        console.log('连接成功');


        mutidata(tablename, inputs.data, inputs.exdata, async function (sql, values) {
            connection.query(sql, values, (err) => { });
        });
        ouputs = "success"
        console.log(ouputs)

        //关闭数据库程序正常退出
        connection.end((err) => {
            if (err) {
                console.error(`关闭连接失败:${err.message}`);
            }
            console.log('成功关闭连接');
        });

    });


}

function mutidata (tablename, data, exdata, callback) {
    for (let index = 0; index < data.length; index++) {
        const element = data[index];
        var keys = Object.keys(element);
        var values = Object.values(element);
        var marks = keys.map(item => '?');

        Object.keys(exdata).map(i => { keys.push(i); marks.push('?') });
        Object.values(exdata).map(i => { values.push(i) });

        var sql_tables = `REPLACE into ${tablename}(${keys.join(', ')}) values(${marks.join(', ')});`;
        callback(sql_tables, values);
    }
}

exports.transform = transform